// pages/device/update/update.js

var cmd = require('../../../command/command.js')
var bluetooth = require('../../../command/bluetooth.js')
var app = getApp()

//64  64原始数据转16进制字符串后为128字节，实测蓝牙每个包最好不要多于200字节
const packLen = 16*6

Page({

  /**
   * 页面的初始数据
   */
  data: {
    percent: 0,
    status: "",
  },

  faildTimeOut : -1,
  checkVersionId : -1, //循环发送版本号查询
  curdataIndex : -1,
  nextdataIndex : -1,
  version : "V100",
  updateContentsArray :[],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      percent : 0
    })
    this.update(app.globalData.updateFilePath)
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("退出更新界面")
    app.globalData.isUpdateting = false
    app.globalData.isReStartUpdate = false
    bluetooth.closeReceive() //关闭更新的监听
    bluetooth.onRecevive() //开启正常的监听流程

    clearTimeout(this.faildTimeOut)
    clearInterval(this.checkVersionId)
  },
  delaySend(data){
    bluetooth.send(data)
  },
  onCallback(res, value){
    clearTimeout(this.faildTimeOut)
    this.faildTimeOut = setTimeout(() => {
      console.warn("响应超时，返回首页")
      wx.navigateBack()
    }, 1*60*1000); //一分钟没有响应判断为更新失败
    
    if(res === 0 && this.curdataIndex != -1){ //next
      const recIndex = parseInt(value, 10) - 1 //下位机返回的包号
      if(recIndex != this.curdataIndex){
        console.error(`发送包出错，包序号不匹配！当前包序号：: ${this.curdataIndex}, 下位机包序号: ${recIndex}`)
      }
      //所有更新包发送完毕
      if(recIndex + 1 == this.updateContentsArray.length){
        console.log("更新包已发完，两秒后进入蓝牙重连，查询版本号判断是否更新成功")
        setTimeout(()=>{ //等待两秒后，发送查询版本号
          
          this.checkVersionId = setInterval(()=>{
            bluetooth.send(cmd.getCommandByName("appVersion"))
          }, 500) 
        
        }, 2000) 
        return
      } else if(recIndex + 1 > this.updateContentsArray.length){
        console.log("超包错误退出")
        return
      }

      this.curdataIndex = recIndex + 1
      this.nextdataIndex = this.curdataIndex + 1
      if(this.curdataIndex < this.updateContentsArray.length){
        this.delaySend(this.updateContentsArray[this.curdataIndex])
      }
        // bluetooth.send(this.updateContentsArray[this.curdataIndex])
    } else if(res === 1){ //retry
      const recIndex = parseInt(value, 10) - 1 //下位机返回的包号
      if(recIndex != this.curdataIndex){
        console.error(`重新发送，包序号不匹配！当前包序号：: ${this.curdataIndex}, 下位机包序号: ${recIndex}`)
        console.error('更新当前包序号为：', recIndex,' ,之后每个包将基于该包递增')
        this.curdataIndex = recIndex
        this.nextdataIndex = this.curdataIndex + 1
      }
      console.warn('重新发送')
      this.delaySend(this.updateContentsArray[this.curdataIndex])
    } else if(res === 2){ //rebegin
      this.curdataIndex = 0
      this.nextdataIndex = 0

      var code = cmd.beginUpdateCommand(value, this.updateContentsArray.length, packLen)
      
      this.delaySend(code)      
      console.warn("从头发送")
    } 
    else if(res === 3){ //更新完成
      if(value == this.version){ //版本号匹配
        console.log("更新完成", value)
      } else{
        console.error(`更新失败，版本号不对！更新包版本号${this.version}, 读取下位机版本号：${value}`)
      }
      console.log("更新完成")
      clearTimeout(this.faildTimeOut)
      clearInterval(this.checkVersionId)
      wx.navigateBack()
    }

    var per = Math.floor(parseInt(this.curdataIndex/this.updateContentsArray.length * 100, 10));
    this.setData({
      percent : per
    })
  },
  update(filePath) {
    app.globalData.isUpdateting = true
    // 同步接口
    try {
      const res = wx.getFileSystemManager().readFileSync( filePath ) //'command/Project(2).bin')
      // const res = fs.readFileSync(`${wx.env.USER_DATA_PATH}/hello.txt`, 'utf8', 0)
      console.log(res.byteLength)
      console.log(res)
      //先将文件才分一个一个包组，并组合成命令准备发送
      
      var count = 1

      for(var i = 0; i < res.byteLength; i += packLen){
        var contents = res.slice(i, i+packLen)
        // console.log(contents)
        var code = cmd.calculateUpdateData(count, contents, packLen)
        // console.log(code)
        this.updateContentsArray.push(code)
        count++
      }
      console.log(this.updateContentsArray)
      
      // console.log(cmd.beginUpdateCommand(this.version, this.updateContentsArray.length, packLen))

      //先关闭正常的监听
      bluetooth.closeReceive()
      //开启更新程序的监听
      bluetooth.onUpdateReceive(this.onCallback)

      if(app.globalData.isReStartUpdate == false){
        //发送更新指令
        const updateCmd = cmd.getCommandByName("update")
        bluetooth.send(updateCmd)

        this.faildTimeOut = setTimeout(() => {
          console.warn("超时，返回首页")
          wx.navigateBack()
        }, 1*60*1000);

      }else{
        //已经直接进入更新过程，不用再发送更新指令
        this.onCallback(2 , app.globalData.restartUpdateVertion)
      }

    } catch(e) {
      console.error(e)
    }
  },
})
